<template>
    <div>
        <div class="ranking">
            <!-- 回到顶部 -->
            <GoToTop></GoToTop>
            <el-row class="ranking-container">

                    <transition name="el-zoom-in-top">
                        <el-col :span="8" class="ranking-list">
                        <div class="rank-title">排行榜单</div>
                    <div @click="showRankingDetail(item.id,index)" :class="isActive===index?'songsheet-list-active':'songsheet-list'" v-for="(item,index) in toplist" :key="item.id" v-hclick="index">
                        <el-image class="toplist-coverimg" :src="item.coverImgUrl"></el-image>
                        <div class="toplist-txt">
                            <div class="toplist-name">{{item.name}}</div>
                            <div class="toplist-updateFrequency">{{item.updateFrequency}}</div>
                        </div>

                    </div>
                    </el-col>
                    </transition>

                <el-col :span="16" class="ranking-detail">
                    <transition name="el-zoom-in-top">
                        <div v-if="loading" class="loading" v-loading="loading" ></div>
                    <el-container class="ranking-detail-container" v-if="!loading">
                        <el-header class="headerinfo">
                             <el-image   class="headerinfo-coverimg" :src="playlist.coverImgUrl?playlist.coverImgUrl:defaultsrc"></el-image>
                            <div class="headerinfo-txt">
                                <div class="headerinfo-name">{{playlist.name}}</div>
                                <div class="headerinfo-updatetime"><i class="el-icon-time"></i> 最近更新：{{playlist.updateTime | dateFormat('YYYY-MM-DD')}}</div>
                                <div class="headerinfo-description">{{playlist.description}}</div>
                            </div>
                        </el-header>
                        <el-main class="songlist">
                            <div class="divide">
                                <div class="divide-title">歌曲列表</div>
                                <span class="divide-amount">{{playlist.trackCount>100?100:playlist.trackCount}}首歌</span>
                                <div class="divide-playcount">播放：<span style="color:rgb(194, 12, 12)">{{playlist.playCount}}</span> 次</div>
                            </div>
                            <!-- 歌曲列表 -->
                            <el-table
                                class="musicTable"
                                :data="musiclist"
                                style="width: 100%"
                                stripe
                                fit
                                :cell-style="{fontSize:'13px'}">
                                <el-table-column
                                    type="index" label="排名" >
                                </el-table-column>
                                <el-table-column
                                    prop="title"
                                    label="歌曲名称"
                                    min-width="35%">
                                    <template v-slot='scope'>
                                        <i v-if="play&&activeIndex===scope.$index" class="el-icon-video-pause" style="cursor: pointer;margin-right:3px" @click="broadcastMusic(scope.$index,scope.row,btnSt='stop')"> {{scope.row.title}}</i>
                                        <i v-else class="el-icon-video-play" style="cursor: pointer;margin-right:3px" @click="broadcastMusic(scope.$index,scope.row,btnSt='broadcast')"> {{scope.row.title}}</i>

                                    </template>
                                </el-table-column>

                                <el-table-column
                                    label="时长"
                                    min-width="20%">
                                    <template v-slot="scope">
                                    {{scope.row.dt | dtFormat}}
                                </template>
                                </el-table-column>
                                <el-table-column
                                    prop="artist"
                                    label="歌手"
                                    min-width="20%">
                                </el-table-column>

                            </el-table>

                        </el-main>
                    </el-container>
                </transition>
                </el-col>

            </el-row>
        </div>
        <!-- 播放器 -->
    <musicplayer @watch="watchplayer" :aplayerVisible="isShow" :musiclist='musiclist' :music="music" ref="musicplayer"></musicplayer>

    </div>
</template>

<script>
// 音乐播放器
import MusicPlayer from '@/views/musicplayer'
// 需要被取消请求的列表
window.cancellist = []
export default {
  components: {
    musicplayer: MusicPlayer
  },
  //   自定义组件
  directives: {
    //   自定义组件 实现进入页面，默认点击第1个列表元素，显示榜单详情
    hclick: {
      inserted (el, binding) {
        // console.log('binding.value:', binding)
        if (binding.value === 0) { // 给for循环第一个元素执行点击事件 相当于index
        //   console.log('inserted:', el, binding)
          el.click()
        }
      }
    }
  },
  data () {
    return {
      // 榜单列表
      toplist: [],
      // 默认图
      defaultsrc: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      //   歌单详情
      playlist: [],
      //   歌曲列表
      musiclist: [],
      play: false,
      //   控制播放器显示
      isShow: false,
      //   歌曲
      music: {},
      // 默认激活列表中第1个元素
      isActive: 0,
      loading: true

    }
  },
  created () {
    //   获取排行榜
    this.getSongToplist()
  },
  methods: {
    //   获取歌曲所有排行榜单
    async getSongToplist () {
      const { data: res } = await this.$http.get('toplist')
      if (res.code !== 200) return this.$message.error('获取音乐榜单失败')
      this.toplist = res.list
      console.log('getSongToplist this.toplist:', this.toplist)
    },

    // 通过 id 获取歌词
    async getSongLrc (songId) {
      try {
        const { data: res } = await this.$http.get('lyric', {
          params: { id: songId },
          cancelToken: new this.$http.CancelToken(function executor (c) {
          // executor 函数接收一个 cancel 函数作为参数
            window.cancellist.push(c)
          })
        })
        if (res.code !== 200) return this.$message.error('获取音乐歌词失败')
        try {
          var songLrc = res.lrc.lyric
          // console.log('songLrc:', songId, songLrc)
          // 如果歌词格式不对，不显示歌词
          if (songLrc.indexOf('[0') === -1) return '[00:00.000] (,,•́ . •̀,,) 抱歉，当前歌曲暂无歌词'
        } catch {
        // console.log('songLrc:', songId, songLrc)
        // 没有歌词时,显示 暂无歌词
          return '[00:00.000] (,,•́ . •̀,,) 抱歉，当前歌曲暂无歌词'
        }
      } catch (error) {
        //   捕获取消请求后报的错
        // console.log(error)
      }

      return songLrc
    },

    //   通过 歌单id 获取歌单详情--榜单也是歌单的一种
    getSongsheetDetail (id) {
      // 显示loading
      this.loading = true
      var songsheetid = id
      //   清空数组，后面重新赋值
      this.musiclist.length = 0
      this.$http.get('playlist/detail', { params: { id: songsheetid } }).then(async ({ data: res }) => {
        if (res.code !== 200) return this.$message.error(res.message)
        // 歌单详情
        this.playlist = res.playlist
        // 歌单封面
        this.coverimgurl = this.playlist.coverImgUrl
        // 歌单名称
        this.songsheetname = this.playlist.name
        // 创建者头像昵称
        this.coveravatarUrl = this.playlist.creator.avatarUrl
        this.covernickname = this.playlist.creator.nickname

        // 因为网易云接口返回的歌曲数量不对，自己取歌曲列表长度为数量
        this.playlist.trackCount = this.playlist.tracks.length

        //   关闭loading
        setTimeout(() => (this.loading = false), 1000)

        // 将歌单详情中 歌曲信息提取存入musiclist   排行榜单只需要取前100个
        this.playlist.tracks.slice(0, 100).forEach(async element => {
          //   console.log(element)
          const songLrc = await this.getSongLrc(element.id)
          this.musiclist.push({
            id: element.id,
            title: element.name,
            artist: element.ar[0].name,
            src: 'https://music.163.com/song/media/outer/url?id=' + element.id + '.mp3',
            pic: element.al.picUrl,
            dt: element.dt,
            lrc: songLrc
          })
        })
        // 分2次给this.musiclist传值是因为getSongLrc响应很慢，先显示歌曲，后面慢慢请求
        // this.musiclist.forEach(async element => {
        //   element.lrc = await this.getSongLrc(element.id)
        //   console.log('getSongsheetDetail getSongLrc element:', element)
        // })
        console.log('getSongsheetDetail getSongLrc this.musiclist:', this.musiclist)
      }).catch(e => {
        //   捕获异常
        console.log('getSongsheetDetail e:', e.response.data.message)
        if (e.response.data.message === 'no resource') return this.$message.error('歌单不存在')
        this.$message.error(e.response.data.message)
      })
    },
    // 显示榜单详情
    showRankingDetail (id, index) {
      // 回到顶部
      document.body.scrollTop = document.documentElement.scrollTop = 0
      // 为了优化性能 在切换页面时， 取消之前的请求
      window.cancellist.forEach(e => {
        e('手动取消')
      })

      // 激活对应的列表元素 修改其样式
      this.isActive = index
      // 获取榜单详情信息
      this.getSongsheetDetail(id)
    },
    // 通过nextTick方法，使播放器组件渲染完成后再执行play方法，防止报错,该play方法从vue-aplayer.vue方法中获得
    thenPlay () {
      this.$nextTick(() => {
        console.log(this.$refs.musicplayer.$refs.aplayer)
        this.$refs.musicplayer.$refs.aplayer.play()
      })
    },
    // 播放音乐
    broadcastMusic (index, scopeRow, btnSt) {
    //   console.log(scopeRow)
      // 显示播放器组件
      this.isShow = true
      // 控制播放/暂停icon的显示
      if (btnSt === 'broadcast') {
        this.activeIndex = index
        this.play = true
      } else {
        this.play = false
      }
      //   try catch 判断是否有currentMusic属性，并捕获异常
      try {
        //   判断是否有currentMusic属性，如果有执行暂停或播放选中的另外一首
        if (this.$refs.musicplayer.$refs.aplayer.currentMusic === scopeRow) {
          this.$refs.musicplayer.$refs.aplayer.toggle()
        } else {
          // 将当前currentMusic属性赋予新的song对象
          this.$refs.musicplayer.$refs.aplayer.currentMusic = scopeRow
          this.thenPlay()
        }
      } catch {
        //   如果没有currentMusic属性，执行播放方法
        this.music = scopeRow
        this.thenPlay()
      }
    },
    // 监听播放器 暂停和播放 事件，获得参数 activeIndex和play，控制歌曲列表中播放按钮的播放与暂停
    watchplayer (index, play) {
      console.log('watch', index, play)
      this.activeIndex = index
      this.play = play
    }
  }
}
</script>

<style scoped>
/* 左侧榜单列表 */
.ranking{
    padding: 10px 10%;
    margin: 0 auto;
    margin-bottom: 100px;
}
.ranking-container{
    max-width: 1080px;
}
.songsheet-list{
    padding: 10px 10px;
    box-sizing: border-box;
    /* 弹性布局 */
    display: flex;
    /* 轴中点对齐 */
    align-items: center;
    /* 左对齐 */
    justify-content: flex-start;
    cursor: pointer;
    transition: 1.2s ease;
}
.rank-title{
    line-height: 25px;
    font-weight: 600;
    color: #333;
}
.songsheet-list:hover{
    background: #e6e6e6;
}
.songsheet-list-active{
    padding: 10px 10px;
    box-sizing: border-box;
    /* 弹性布局 */
    display: flex;
    /* 轴中点对齐 */
    align-items: center;
    /* 左对齐 */
    justify-content: flex-start;
    cursor: pointer;
    transition: 1.2s ease;
    background: #e6e6e6;
}
.songsheet-list-active .toplist-coverimg{
    /* 控制图片变大 */
    transition: .3s ease;
    width: 50px;
    border-radius: 4px;
}
.toplist-coverimg{
    transition: .3s ease;
    width: 40px;
    border-radius: 4px;
}
.toplist-txt{
    /* 平分控件 */
    flex: 1;
    padding: 0 10px;
    box-sizing: border-box;
    line-height: 20px;
    font-size: 12px;
    margin-left: 2%;
}
/* 右侧榜单内容 */
.headerinfo{
    display: flex;
    height: 230px !important;
    padding: 40px;
}
.headerinfo-coverimg{
    width: 150px;
    /* height: 150px; */
    border-radius: 4px;
    /* overflow: hidden; */
}
.headerinfo-txt{
    padding: 10px;
    width: 70%;
}
.headerinfo-name{
    line-height: 25px;
    font-size: 20px;
    font-weight: 400;
}
.headerinfo-updatetime{
    line-height: 35px;
    color: #666;
    font-size: 12px;
}
.headerinfo-description{
    line-height: 35px;
    color: #666;
    font-size: 12px;
}
.divide{
    position: relative;
    display: flex;
    padding: 0 10px;
    border-bottom: 1px solid rgb(255, 99, 72);
}
.divide-title{
    line-height: 25px;
    font-size: 16px;
    font-weight: 500;
    color: #333;
}
/* 分割区 */
.divide-amount{
    margin-left: 5px;
    line-height: 25px;
    font-size: 13px;
    font-weight: 500;
    color: #333;
}
.divide-playcount{
    position: absolute;
    right: 0px;
    font-size: 13px;
    font-weight: 500;
    color: #333;
}
/* loading */
.loading{
    /* 将loading脱离文档流，防止占用高度、使得详情内容加载时从中间显示出来 */
    position: absolute;
    top: 0px;
    height: 200px;
    width: 100%;
}
/* 修改loading图标颜色 */
>>>.el-loading-spinner .path{
    stroke: #2f3542;
}
>>>.el-loading-mask{
    z-index: 2 ;
    /* background:red !important */
}
/* 榜单列表 */
.ranking-list{
    min-width: 200px;
    /* border:1px solid red */
}
/* 详情 */
.ranking-detail{
    /* border:2px solid blue; */
    /* 防止loading以main为定位对象 */
    position: relative;
}
/* 详情容器 */
.ranking-detail-container{

    /* border: 1px solid red; */
    /* height: 1000px; */
}
</style>
